package com.main.listener;


import com.alibaba.fastjson.JSON;
import com.main.common.BaseContext;
import com.main.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录检查过滤器
 *
 * @author zhouRuoYu
 * @date 2022/10/02
 */
@Slf4j
@WebFilter(filterName = "LoginCheckFilter", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

    private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //1、获取请求URI
        String requestURI = request.getRequestURI();//   /user/loginAccount
//        StringBuffer requestURL = request.getRequestURL();//   http://localhost/user/loginAccount

        //定义不需要处理的请求路径
        String[] urls = {
                "/user/sendMail",
                "/user/login",
                "/user/loginAccount",
                "/user/logout",

                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"
        };

        //2、判断本次请求是否要处理
        boolean check = check(urls, requestURI);
        System.out.println("check:" + check);

        //3、不需要处理则进行放行
        if (check) {
            log.info("本次请求{}不需要处理", requestURI);
            filterChain.doFilter(request, response);
            return;
        }

        //4、判断《用户》登陆状态，如果已经登录，则直接放行
        Long user = (Long) request.getSession().getAttribute("user");
        if (user != null) {
            log.info("用户已登录IDL：{}", user);
            BaseContext.setCurrentId(user);//将登录用户id加入到ThreadLocal中
            filterChain.doFilter(request, response);
            return;
        }

        //4、判断《商户》登陆状态，如果已经登录，则直接放行

        //4、判断《管理》登陆状态，如果已经登录，则直接放行

        log.info("用户未登录");
        response.getWriter().write(JSON.toJSONString(R.success("NO_LONG")));
    }

    private boolean check(String[] urls, String requestURI) {
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);//判断是否为，忽略的路径，是则为true
            if (match) return true;
        }
        return false;
    }

}
